package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 认证状态
 * 对所有控制层并使用了@GuiGuLogin注解的方法进行增强
 * 切面类
 */
@Aspect //声明切面类
@Component
@Slf4j
public class GuiGuLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) &&  @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        // 前置逻辑
        // 获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        // 从对象中获取token
        String token = request.getHeader("token");
        //查询redis中的用户信息
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo)redisTemplate.opsForValue().get(loginKey);

        //如果用户信息为空，且目标方法需要登陆访问，返回状态码208
        if (userInfoVo == null && guiGuLogin.required()){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 如果用户信息不为空, 将用户信息存入threadlocal
        if (userInfoVo != null){
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        Object retVal = pjp.proceed();
        // 后置逻辑
        // 清理threadlocal
        AuthContextHolder.removeUserId();
        return retVal;
    }
}